package com.ccsc.auth.realm;

import com.alibaba.fastjson.JSONObject;
import com.ccsc.auth.entity.ShiroSysUser;
import com.ccsc.auth.entity.ShiroUser;
import com.ccsc.auth.utils.SslUtil;
import com.google.common.base.Strings;
import com.google.common.collect.Sets;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cas.CasRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by XingWen on 2016/4/2.
 */
public class ShiroRealm extends CasRealm {

//    static {
//        //for localhost testing only
//        javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
//                new javax.net.ssl.HostnameVerifier(){
//
//                    public boolean verify(String hostname,
//                                          javax.net.ssl.SSLSession sslSession) {
//                        if (hostname.equals("cas.wish.me")) {
//                            return true;
//                        }
//                        return false;
//                    }
//                });
//    }

    protected final Map<String, SimpleAuthorizationInfo> roles = new ConcurrentHashMap<String, SimpleAuthorizationInfo>();

    /**
     * 为当前登录的Subject授予角色和权限
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){
        String username = (String)principals.getPrimaryPrincipal();
        System.out.println("当前登录用户："+username);
        if(!Strings.isNullOrEmpty(username)){
            SimpleAuthorizationInfo authenticationInfo = new SimpleAuthorizationInfo();
            try {
                Set<String> roleSet = Sets.newHashSet();
                Set<String> permSet = Sets.newHashSet();

                authenticationInfo.addRoles(roleSet);
                authenticationInfo.addStringPermissions(permSet);
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }
            return authenticationInfo;
        }
        return null;
    }


    /**
     * 验证当前登录的Subject
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {

//        try {
//            SslUtil.ignoreSsl();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        AuthenticationInfo authc = super.doGetAuthenticationInfo(authcToken);
        String account = (String) authc.getPrincipals().getPrimaryPrincipal();
        ShiroSysUser shiroSysUser = new ShiroSysUser();

        try {
            PrincipalCollection principalCollection = authc.getPrincipals();
            if(principalCollection!=null && !principalCollection.isEmpty()){
                List<Map<String,String>> principalsList = principalCollection.asList();
                Map<String,String> attributes = principalsList.get(1);
//                String shiroUserJson = URLDecoder.decode(attributes.get("casUserInfo"),"UTF-8");
                String shiroUserJson = attributes.get("casUserInfo");
                System.out.println(account + ":" + shiroUserJson);
                shiroSysUser = JSONObject.parseObject(shiroUserJson, ShiroSysUser.class);
            }

            Subject currentUser = SecurityUtils.getSubject();
            Session session = currentUser.getSession();
            session.setAttribute("loginSysUser", shiroSysUser);
            return authc;
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
            return null;
        }
    }

    //清除用户的权限缓存
    public void clearAuthz(){
        this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }
}